/**
 * 统一API服务
 * 重新设计的API调用服务，提供类型安全和完善的错误处理
 */

import {
  httpGet,
  httpPost,
  httpPut,
  httpDelete,
  httpUpload,
} from "../utils/http";
import { API_ENDPOINTS } from "../config/env";
import {
  ApiResponse,
  LoginRequest,
  LoginResponse,
  RegisterRequest,
  SendCodeRequest,
  UserInfo,
  ClassInfo,
  CreateClassRequest,
  ClassMember,
  FileInfo,
  AddFileRequest,
  UploadResponse,
  AdviceInfo,
  AddAdviceRequest,
  FeedbackAdviceRequest,
  ExamInfo,
  AddExamRequest,
  TopicInfo,
  AddTopicRequest,
  CommentInfo,
  AddCommentRequest,
  DashboardStats,
  ChatRequest,
  ChatResponse,
  GenerateQuestionsRequest,
  QuestionInfo,
  SystemSettings,
  HealthCheckResponse,
  CommonQueryParams,
  PaginationParams,
} from "../types/api";

// =============================================================================
// API服务基础类
// =============================================================================

/**
 * API服务基础类
 * 提供统一的错误处理和日志记录
 */
abstract class BaseAPIService {
  /**
   * 处理API响应
   */
  protected async handleResponse<T>(
    promise: Promise<ApiResponse<T>>,
    operation: string
  ): Promise<T> {
    try {
      console.log(`🚀 API调用: ${operation}`);
      const response = await promise;

      if (response.code === 0) {
        console.log(`✅ API成功: ${operation}`, response.data);
        return response.data;
      } else {
        console.warn(`⚠️ API业务错误: ${operation}`, response);
        throw new Error(response.msg || "操作失败");
      }
    } catch (error: any) {
      console.error(`❌ API错误: ${operation}`, error);

      // 统一错误处理
      if (error.response?.status === 401) {
        throw new Error("登录已过期，请重新登录");
      } else if (error.response?.status === 403) {
        throw new Error("权限不足");
      } else if (error.response?.status === 404) {
        throw new Error("请求的资源不存在");
      } else if (error.response?.status >= 500) {
        throw new Error("服务器错误，请稍后重试");
      } else if (
        error.code === "ECONNREFUSED" ||
        error.code === "NETWORK_ERROR"
      ) {
        throw new Error("网络连接失败，请检查网络或后端服务");
      } else {
        throw new Error(error.message || "操作失败");
      }
    }
  }

  /**
   * 处理文件上传响应
   */
  protected async handleUploadResponse(
    promise: Promise<UploadResponse>,
    operation: string
  ): Promise<UploadResponse> {
    try {
      console.log(`📤 文件上传: ${operation}`);
      const response = await promise;
      console.log(`✅ 上传成功: ${operation}`, response);
      return response;
    } catch (error: any) {
      console.error(`❌ 上传失败: ${operation}`, error);
      throw new Error(error.message || "文件上传失败");
    }
  }
}

// =============================================================================
// 认证服务
// =============================================================================

class AuthAPIService extends BaseAPIService {
  /**
   * 用户登录
   */
  async login(data: LoginRequest): Promise<LoginResponse> {
    const sanitizedData = { ...data, password: "***" };
    console.log("🔐 登录请求:", sanitizedData);

    return this.handleResponse(
      httpPost<ApiResponse<LoginResponse>>(API_ENDPOINTS.AUTH.LOGIN, data),
      "用户登录"
    );
  }

  /**
   * 用户注册
   */
  async register(data: RegisterRequest): Promise<void> {
    const sanitizedData = { ...data, password: "***" };
    console.log("📝 注册请求:", sanitizedData);

    return this.handleResponse(
      httpPost<ApiResponse<void>>(API_ENDPOINTS.AUTH.REGISTER, data),
      "用户注册"
    );
  }

  /**
   * 发送验证码
   */
  async sendCode(data: SendCodeRequest): Promise<void> {
    return this.handleResponse(
      httpPost<ApiResponse<void>>(API_ENDPOINTS.AUTH.SEND_CODE, data),
      "发送验证码"
    );
  }

  /**
   * 获取用户信息
   */
  async getUserInfo(): Promise<UserInfo> {
    return this.handleResponse(
      httpGet<ApiResponse<UserInfo>>(API_ENDPOINTS.AUTH.USER_INFO),
      "获取用户信息"
    );
  }

  /**
   * 用户登出
   */
  async logout(): Promise<void> {
    return this.handleResponse(
      httpPost<ApiResponse<void>>(API_ENDPOINTS.AUTH.LOGOUT),
      "用户登出"
    );
  }

  /**
   * 获取图形验证码
   */
  async getCaptcha(): Promise<Blob> {
    try {
      console.log("🖼️ 获取验证码");
      const response = await httpGet(API_ENDPOINTS.AUTH.CAPTCHA, undefined, {
        responseType: "blob",
      });
      console.log("✅ 验证码获取成功");
      return response;
    } catch (error) {
      console.error("❌ 验证码获取失败:", error);
      throw new Error("验证码获取失败");
    }
  }

  /**
   * 刷新Token
   */
  async refreshToken(): Promise<{ token: string }> {
    return this.handleResponse(
      httpPost<ApiResponse<{ token: string }>>("/api/v1/auth/refresh"),
      "Token刷新"
    );
  }
}

// =============================================================================
// 班级管理服务
// =============================================================================

class ClassAPIService extends BaseAPIService {
  /**
   * 获取班级列表
   */
  async getClasses(params?: CommonQueryParams): Promise<ClassInfo[]> {
    return this.handleResponse(
      httpGet<ApiResponse<ClassInfo[]>>(
        API_ENDPOINTS.TEACHER.LIST_CLASS,
        params
      ),
      "获取班级列表"
    );
  }

  /**
   * 创建班级
   */
  async createClass(data: CreateClassRequest): Promise<ClassInfo> {
    return this.handleResponse(
      httpPost<ApiResponse<ClassInfo>>(
        API_ENDPOINTS.TEACHER.CREATE_CLASS,
        data
      ),
      "创建班级"
    );
  }

  /**
   * 获取班级详情
   */
  async getClassInfo(classId: number): Promise<ClassInfo> {
    return this.handleResponse(
      httpGet<ApiResponse<ClassInfo>>(
        `${API_ENDPOINTS.TEACHER.INFO_CLASS}/${classId}`
      ),
      "获取班级详情"
    );
  }

  /**
   * 删除班级
   */
  async deleteClass(classId: number): Promise<void> {
    return this.handleResponse(
      httpDelete<ApiResponse<void>>(
        `${API_ENDPOINTS.TEACHER.DELETE_CLASS}/${classId}`
      ),
      "删除班级"
    );
  }

  /**
   * 获取班级成员列表
   */
  async getClassMembers(
    classId: number,
    status: "pending" | "active" = "active"
  ): Promise<ClassMember[]> {
    const allow = status === "active" ? 1 : 0;
    return this.handleResponse(
      httpGet<ApiResponse<ClassMember[]>>(
        `${API_ENDPOINTS.TEACHER.ATTEND_LIST}/${classId}?allow=${allow}`
      ),
      "获取班级成员"
    );
  }

  /**
   * 批准学生入班申请
   */
  async approveStudent(studentId: string, classId: number): Promise<void> {
    return this.handleResponse(
      httpPost<ApiResponse<void>>(
        `${API_ENDPOINTS.TEACHER.ALLOW_STUDENT}?stuId=${studentId}&classId=${classId}`
      ),
      "批准学生入班"
    );
  }

  /**
   * 学生申请加入班级
   */
  async joinClass(classId: number): Promise<void> {
    return this.handleResponse(
      httpPost<ApiResponse<void>>(
        `${API_ENDPOINTS.STUDENT.ADD_CLASS}?classId=${classId}`
      ),
      "申请加入班级"
    );
  }
}

// =============================================================================
// 文件管理服务
// =============================================================================

class FileAPIService extends BaseAPIService {
  /**
   * 上传文件
   */
  async uploadFile(
    file: File,
    onProgress?: (progress: number) => void
  ): Promise<UploadResponse> {
    return this.handleUploadResponse(
      httpUpload(API_ENDPOINTS.TEACHER.UPLOAD_FILE, file, onProgress),
      `上传文件: ${file.name}`
    );
  }

  /**
   * 添加课堂文件
   */
  async addFile(data: AddFileRequest): Promise<FileInfo> {
    return this.handleResponse(
      httpPost<ApiResponse<FileInfo>>(API_ENDPOINTS.TEACHER.ADD_FILE, data),
      "添加课堂文件"
    );
  }

  /**
   * 获取文件列表
   */
  async getFiles(classId: number): Promise<FileInfo[]> {
    return this.handleResponse(
      httpGet<ApiResponse<FileInfo[]>>(
        `${API_ENDPOINTS.TEACHER.LIST_FILE}?classId=${classId}`
      ),
      "获取文件列表"
    );
  }

  /**
   * 发布文件
   */
  async publishFile(fileId: number): Promise<void> {
    return this.handleResponse(
      httpPut<ApiResponse<void>>(
        `${API_ENDPOINTS.TEACHER.PUBLISH_FILE}?fileId=${fileId}`
      ),
      "发布文件"
    );
  }

  /**
   * 删除文件
   */
  async deleteFile(fileId: number): Promise<void> {
    return this.handleResponse(
      httpDelete<ApiResponse<void>>(
        `${API_ENDPOINTS.TEACHER.DELETE_FILE}?fileId=${fileId}`
      ),
      "删除文件"
    );
  }

  /**
   * 学生获取文件
   */
  async getStudentFiles(classId: number): Promise<FileInfo[]> {
    return this.handleResponse(
      httpGet<ApiResponse<FileInfo[]>>(
        `${API_ENDPOINTS.STUDENT.GET_FILE}/${classId}`
      ),
      "获取学习资源"
    );
  }
}

// =============================================================================
// 建议反馈服务
// =============================================================================

class AdviceAPIService extends BaseAPIService {
  /**
   * 获取建议列表
   */
  async getAdviceList(
    classId: number,
    params?: PaginationParams
  ): Promise<AdviceInfo[]> {
    return this.handleResponse(
      httpGet<ApiResponse<AdviceInfo[]>>(
        `${API_ENDPOINTS.TEACHER.LIST_ADVICE}?class_id=${classId}`,
        params
      ),
      "获取建议列表"
    );
  }

  /**
   * 添加建议
   */
  async addAdvice(data: AddAdviceRequest): Promise<AdviceInfo> {
    return this.handleResponse(
      httpPost<ApiResponse<AdviceInfo>>(API_ENDPOINTS.STUDENT.ADD_ADVICE, data),
      "添加建议"
    );
  }

  /**
   * 反馈建议
   */
  async feedbackAdvice(data: FeedbackAdviceRequest): Promise<void> {
    return this.handleResponse(
      httpPost<ApiResponse<void>>(API_ENDPOINTS.TEACHER.FEEDBACK_ADVICE, data),
      "反馈建议"
    );
  }
}

// =============================================================================
// 考试管理服务
// =============================================================================

class ExamAPIService extends BaseAPIService {
  /**
   * 获取考试列表
   */
  async getExams(
    classId: number,
    params?: CommonQueryParams
  ): Promise<ExamInfo[]> {
    return this.handleResponse(
      httpGet<ApiResponse<ExamInfo[]>>(
        `${API_ENDPOINTS.TEACHER.LIST_EXAM}?class_id=${classId}`,
        params
      ),
      "获取考试列表"
    );
  }

  /**
   * 添加考试
   */
  async addExam(data: AddExamRequest): Promise<ExamInfo> {
    return this.handleResponse(
      httpPost<ApiResponse<ExamInfo>>(API_ENDPOINTS.TEACHER.ADD_EXAM, data),
      "添加考试"
    );
  }

  /**
   * 获取考试详情
   */
  async getExamDetail(examId: number): Promise<ExamInfo> {
    return this.handleResponse(
      httpGet<ApiResponse<ExamInfo>>(
        `${API_ENDPOINTS.TEACHER.LIST_EXAM}/${examId}`
      ),
      "获取考试详情"
    );
  }

  /**
   * AI生成考试题目
   */
  async generateQuestions(
    data: GenerateQuestionsRequest
  ): Promise<QuestionInfo[]> {
    return this.handleResponse(
      httpPost<ApiResponse<QuestionInfo[]>>(
        API_ENDPOINTS.EXAM.AI_GENERATE,
        data
      ),
      "AI生成题目"
    );
  }
}

// =============================================================================
// 话题讨论服务
// =============================================================================

class DiscussionAPIService extends BaseAPIService {
  /**
   * 获取话题列表
   */
  async getTopics(
    params: { classId?: number } & CommonQueryParams
  ): Promise<TopicInfo[]> {
    return this.handleResponse(
      httpGet<ApiResponse<TopicInfo[]>>(
        API_ENDPOINTS.STUDENT.LIST_TOPIC,
        params
      ),
      "获取话题列表"
    );
  }

  /**
   * 添加话题
   */
  async addTopic(data: AddTopicRequest): Promise<TopicInfo> {
    return this.handleResponse(
      httpPost<ApiResponse<TopicInfo>>(API_ENDPOINTS.STUDENT.ADD_TOPIC, data),
      "添加话题"
    );
  }

  /**
   * 删除话题
   */
  async deleteTopic(topicId: number): Promise<void> {
    return this.handleResponse(
      httpDelete<ApiResponse<void>>(
        `${API_ENDPOINTS.STUDENT.DEL_TOPIC}?topic_id=${topicId}`
      ),
      "删除话题"
    );
  }

  /**
   * 点赞话题
   */
  async likeTopic(topicId: number): Promise<void> {
    return this.handleResponse(
      httpPost<ApiResponse<void>>(
        `${API_ENDPOINTS.STUDENT.GOOD_TOPIC}?topic_id=${topicId}`
      ),
      "点赞话题"
    );
  }

  /**
   * 获取评论列表
   */
  async getComments(
    topicId: number,
    page: number = 1,
    size: number = 10
  ): Promise<CommentInfo[]> {
    return this.handleResponse(
      httpGet<ApiResponse<CommentInfo[]>>(
        `${API_ENDPOINTS.STUDENT.LIST_COMMENT}?topic_id=${topicId}&page=${page}&size=${size}`
      ),
      "获取评论列表"
    );
  }

  /**
   * 添加评论
   */
  async addComment(data: AddCommentRequest): Promise<CommentInfo> {
    return this.handleResponse(
      httpPost<ApiResponse<CommentInfo>>(
        API_ENDPOINTS.STUDENT.ADD_COMMENT,
        data
      ),
      "添加评论"
    );
  }

  /**
   * 删除评论
   */
  async deleteComment(commentId: number): Promise<void> {
    return this.handleResponse(
      httpDelete<ApiResponse<void>>(
        `${API_ENDPOINTS.STUDENT.DEL_COMMENT}?comment_id=${commentId}`
      ),
      "删除评论"
    );
  }
}

// =============================================================================
// AI服务
// =============================================================================

class AIAPIService extends BaseAPIService {
  private pythonAIBaseUrl = "http://localhost:8000"; // Python AI服务地址

  // 获取默认用户信息
  private getDefaultUserInfo() {
    try {
      const userStr = localStorage.getItem('user');
      const user = userStr ? JSON.parse(userStr) : null;
      return {
        account_id: user?.id?.toString() || "default_user",
        course_id: user?.currentCourseId?.toString() || "default_course"
      };
    } catch (error) {
      console.warn("获取用户信息失败，使用默认值", error);
      return {
        account_id: "default_user",
        course_id: "default_course"
      };
    }
  }

  /**
   * AI聊天 - 调用Python AI服务
   */
  async chat(data: ChatRequest): Promise<ChatResponse> {
    try {
      const userInfo = this.getDefaultUserInfo();
      
      const response = await fetch(`${this.pythonAIBaseUrl}/api/teach/chat`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          message: data.message,
          account_id: userInfo.account_id,
          course_id: userInfo.course_id,
        }),
      });

      if (!response.ok) {
        throw new Error(`AI聊天失败: ${response.status}`);
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error("无法获取响应流");
      }

      let fullResponse = "";
      const decoder = new TextDecoder();

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        fullResponse += chunk;
      }

      return {
        message: fullResponse || "AI服务暂时无响应",
        conversationId: userInfo.account_id,
        timestamp: new Date().toISOString(),
      };
    } catch (error) {
      console.error("❌ Python AI聊天失败:", error);
      throw new Error("AI聊天失败");
    }
  }

  /**
   * AI流式聊天 - 直接返回响应流
   */
  async streamChat(data: ChatRequest): Promise<ReadableStream> {
    try {
      console.log("🤖 Python AI流式聊天:", data.message);
      const userInfo = this.getDefaultUserInfo();
      
      const response = await fetch(`${this.pythonAIBaseUrl}/api/teach/chat`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          message: data.message,
          account_id: userInfo.account_id,
          course_id: userInfo.course_id,
        }),
      });

      if (!response.ok) {
        throw new Error("流式聊天失败");
      }

      return response.body!;
    } catch (error) {
      console.error("❌ Python AI流式聊天失败:", error);
      throw new Error("流式聊天失败");
    }
  }

  /**
   * AI评论分析
   */
  async analyzeComment(comments: string): Promise<any> {
    try {
      const response = await fetch(`${this.pythonAIBaseUrl}/api/teach/comment`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ comments }),
      });

      if (!response.ok) {
        throw new Error("评论分析失败");
      }

      const result = await response.json();
      return result;
    } catch (error) {
      console.error("❌ AI评论分析失败:", error);
      throw new Error("评论分析失败");
    }
  }

  /**
   * AI文件处理
   */
  async processFile(file: File, courseId?: string, fileId?: string): Promise<any> {
    try {
      const formData = new FormData();
      formData.append('file', file);
      if (courseId) formData.append('course_id', courseId);
      if (fileId) formData.append('file_id', fileId);

      const response = await fetch(`${this.pythonAIBaseUrl}/api/teach/upload`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("文件处理失败");
      }

      const result = await response.json();
      return result;
    } catch (error) {
      console.error("❌ AI文件处理失败:", error);
      throw new Error("文件处理失败");
    }
  }

  /**
   * 生成文件大纲
   */
  async generateOutline(file: File): Promise<ReadableStream> {
    try {
      const formData = new FormData();
      formData.append('file', file);

      const response = await fetch(`${this.pythonAIBaseUrl}/api/file/outline`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("生成大纲失败");
      }

      return response.body!;
    } catch (error) {
      console.error("❌ 生成大纲失败:", error);
      throw new Error("生成大纲失败");
    }
  }

  /**
   * 生成考试题目
   */
  async generateExam(file: File, knowledgePoint: string): Promise<ReadableStream> {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('knowledge_point', knowledgePoint);

      const response = await fetch(`${this.pythonAIBaseUrl}/api/file/exam`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("生成考试题目失败");
      }

      return response.body!;
    } catch (error) {
      console.error("❌ 生成考试题目失败:", error);
      throw new Error("生成考试题目失败");
    }
  }

  /**
   * 生成PPT
   */
  async generatePPT(file: File, pages: number): Promise<Blob> {
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('pages', pages.toString());

      const response = await fetch(`${this.pythonAIBaseUrl}/api/file/ppt`, {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        throw new Error("生成PPT失败");
      }

      return await response.blob();
    } catch (error) {
      console.error("❌ 生成PPT失败:", error);
      throw new Error("生成PPT失败");
    }
  }
}

// =============================================================================
// 仪表板服务
// =============================================================================

class DashboardAPIService extends BaseAPIService {
  /**
   * 获取仪表板统计数据
   */
  async getStats(): Promise<DashboardStats> {
    // 由于后端暂时没有统计接口，我们组合多个接口的数据
    try {
      const [classes, advice, exams] = await Promise.all([
        this.handleResponse(
          httpGet<ApiResponse<ClassInfo[]>>(API_ENDPOINTS.TEACHER.LIST_CLASS),
          "获取班级统计"
        ),
        this.handleResponse(
          httpGet<ApiResponse<AdviceInfo[]>>(API_ENDPOINTS.TEACHER.LIST_ADVICE),
          "获取建议统计"
        ),
        this.handleResponse(
          httpGet<ApiResponse<ExamInfo[]>>(API_ENDPOINTS.TEACHER.LIST_EXAM),
          "获取考试统计"
        ),
      ]);

      return {
        totalClasses: classes.length,
        totalStudents: 0, // 需要遍历班级获取学生数
        totalExams: exams.length,
        totalFiles: 0, // 需要获取文件统计
        recentActivities: [], // 需要活动记录
      };
    } catch (error) {
      console.error("❌ 获取统计数据失败:", error);
      throw new Error("获取统计数据失败");
    }
  }
}

// =============================================================================
// 健康检查服务
// =============================================================================

class HealthAPIService extends BaseAPIService {
  /**
   * 检查API健康状态
   */
  async checkHealth(): Promise<HealthCheckResponse> {
    try {
      console.log("🔍 检查API健康状态");
      const response = await httpGet("/api/health", undefined, {
        useCache: false,
      });

      return {
        status: "healthy",
        timestamp: new Date().toISOString(),
        services: {
          database: "healthy",
        },
      };
    } catch (error) {
      console.error("❌ 健康检查失败:", error);
      return {
        status: "unhealthy",
        timestamp: new Date().toISOString(),
        services: {
          database: "unhealthy",
        },
      };
    }
  }

  /**
   * 检查认证状态
   */
  async checkAuth(): Promise<{ status: string; user?: UserInfo }> {
    try {
      const user = await new AuthAPIService().getUserInfo();
      return { status: "authenticated", user };
    } catch (error) {
      return { status: "unauthenticated" };
    }
  }
}

// =============================================================================
// 创建服务实例
// =============================================================================

export const authAPI = new AuthAPIService();
export const classAPI = new ClassAPIService();
export const fileAPI = new FileAPIService();
export const adviceAPI = new AdviceAPIService();
export const examAPI = new ExamAPIService();
export const discussionAPI = new DiscussionAPIService();
export const aiAPI = new AIAPIService();
export const dashboardAPI = new DashboardAPIService();
export const healthAPI = new HealthAPIService();

// =============================================================================
// 默认导出所有API服务
// =============================================================================

export default {
  auth: authAPI,
  class: classAPI,
  file: fileAPI,
  advice: adviceAPI,
  exam: examAPI,
  discussion: discussionAPI,
  ai: aiAPI,
  dashboard: dashboardAPI,
  health: healthAPI,
};

// =============================================================================
// 兼容性导出（保持与旧版本的兼容性）
// =============================================================================

export const teacherAPI = {
  getClasses: classAPI.getClasses.bind(classAPI),
  createClass: classAPI.createClass.bind(classAPI),
  getStudents: classAPI.getClassMembers.bind(classAPI),
  allowStudent: classAPI.approveStudent.bind(classAPI),
  uploadFile: fileAPI.uploadFile.bind(fileAPI),
  addFile: fileAPI.addFile.bind(fileAPI),
  getFileList: fileAPI.getFiles.bind(fileAPI),
  publishFile: fileAPI.publishFile.bind(fileAPI),
  deleteFile: fileAPI.deleteFile.bind(fileAPI),
  getAdviceList: adviceAPI.getAdviceList.bind(adviceAPI),
  feedbackAdvice: adviceAPI.feedbackAdvice.bind(adviceAPI),
  addExam: examAPI.addExam.bind(examAPI),
  getExamList: examAPI.getExams.bind(examAPI),
};

export const studentAPI = {
  addToClass: classAPI.joinClass.bind(classAPI),
  getClassInfo: classAPI.getClassInfo.bind(classAPI),
  getResources: fileAPI.getStudentFiles.bind(fileAPI),
  uploadFile: fileAPI.uploadFile.bind(fileAPI),
  addAdvice: adviceAPI.addAdvice.bind(adviceAPI),
  getAdviceList: adviceAPI.getAdviceList.bind(adviceAPI),
  addTopic: discussionAPI.addTopic.bind(discussionAPI),
  getTopicList: discussionAPI.getTopics.bind(discussionAPI),
  deleteTopic: discussionAPI.deleteTopic.bind(discussionAPI),
  likeTopic: discussionAPI.likeTopic.bind(discussionAPI),
  addComment: discussionAPI.addComment.bind(discussionAPI),
  getCommentList: discussionAPI.getComments.bind(discussionAPI),
  deleteComment: discussionAPI.deleteComment.bind(discussionAPI),
};
